<template>
  <!-- 调拨详细 -->
  <div class="supplier-detail">
    <!-- 上方容器：调拨基础资料 -->
    <div class="basic-info-container">
      <div class="section-header">
        <div class="section-title">调拨单号：{{ supplierForm.al_code }}</div>
        <div class="section-actions">
          <el-button size="small" @click="JumptoEdit">编辑</el-button>
          <el-button size="small" @click="deleteAllot">删除</el-button>
        </div>
      </div>
      <div class="divider"></div>
      <!-- 使用网格布局的基础资料部分 -->
      <div class="basic-info-grid">
        <div class="info-item">
          <div class="info-label">制单人</div>
          <div class="info-value">{{supplierForm.create_name}}</div>
        </div>
        <div class="info-item">
          <div class="info-label">制单时间</div>
          <div class="info-value">{{ supplierForm.create_time }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">单据状态</div>
          <div class="info-value">{{ supplierForm.al_status_label }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">调拨类型</div>
          <div class="info-value">{{ supplierForm.al_type }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">调拨申请日期</div>
          <div class="info-value">{{ supplierForm.al_date }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">调出仓库</div>
          <div class="info-value">{{ supplierForm.out_wh_name }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">调入仓库</div>
          <div class="info-value">{{ supplierForm.in_wh_name }}</div>
        </div>
        <div class="info-item">
          <div class="info-label">经办人</div>
          <div class="info-value">{{ supplierForm.al_user }}</div>
        </div>
        <!-- 备注跨2列 -->
        <div class="info-item full-row">
          <div class="info-label">备注</div>
          <div class="info-value">{{ supplierForm.remark }}</div>
        </div>
      </div>
    </div>
    <!-- 下方容器：其他信息 -->
    <div class="other-info-container">
      <div class="section-header">
        <div class="section-tabs">
          <div
            v-for="(tab, index) in tabs"
            :key="index"
            :class="['tab-item', { active: activeTab === tab }]"
            @click="activeTab = tab">
            {{ tab }}
          </div>
        </div>
      </div>
      <div class="divider"></div>
      <div v-if="activeTab === '其他信息'" class="tab-content">
        <div class="section-header">
          <div class="section-title">附件</div>
        </div>
        <el-table
          :data="filelist"
          @row-click="handleRowClick"
          style="width: 100%"
          >
          <el-table-column label="文件名">
            <template #default="scope">
              <el-link type="primary" :underline="false">
                <el-icon><Document /></el-icon>
                <span style="margin-left: 8px">{{ scope.row.title }}</span>
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="activeTab === '调拨明细'" class="tab-content">
          <div style="text-align: left;">
              <el-button @click="exportData()">导出</el-button>
          </div>
          <!--表格-->
          <el-table :data="purdata"  stripe style="margin-top: 10px;" @selection-change="SelectChange">
            <el-table-column fixed  type="selection"></el-table-column>
            <el-table-column fixed prop="ald_id" label="序号"></el-table-column>
            <el-table-column fixed prop="proc_name" label="货品名称"></el-table-column>
            <el-table-column fixed prop="proc_code" label="货品编号" width="160px"></el-table-column>
            <el-table-column prop="proc_model" label="规格型号"></el-table-column>
            <el-table-column prop="proc_primary_unit" label="单位"></el-table-column>
            <el-table-column prop="type_name" label="货品类型"></el-table-column>
            <el-table-column prop="out_wh_num" label="调出仓当前库存" width="200px"></el-table-column>
            <el-table-column prop="in_wh_num" label="调入仓当前库存" width="200px"></el-table-column>
            <el-table-column prop="ald_num" label="调拨数量"></el-table-column>
            <el-table-column prop="ald_price" label="调拨单价"></el-table-column>
            <el-table-column prop="ald_total"  label="调拨金额" ></el-table-column>
            <el-table-column label="出库状态" width="150">
              <template #default="scope">
                {{scope.row.out_wh_stock}}({{scope.row.ald_outstockOK_num}}/{{scope.row.out_wh_num}})
              </template>
            </el-table-column>
            <el-table-column label="入库状态" width="150">
              <template #default="scope">
                {{scope.row.out_wh_stock}}({{scope.row.ald_instockOK_num}}/{{scope.row.out_wh_num}})
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="400px"></el-table-column>
          </el-table>
          <!-- 调拨明细合计行 -->
          <div class="summary-row">
              <span>合计</span>
              <div>
                  <span class="summary-item">调拨种类: <b style="color: #e6a23c;">{{ allotSummary.categories }}</b></span>
                  <span class="summary-item">调拨数量: <b style="color: #e6a23c;">{{ allotSummary.totalNum }}</b></span>
                  <span class="summary-item">调拨金额: <b style="color: #e6a23c;">{{ allotSummary.totalAmount }}</b></span>
              </div>
          </div>
      </div>
      <div v-if="activeTab === '出库记录'" class="tab-content">
        <!-- 导出按钮 -->
        <div style="text-align: left; margin-bottom: 10px;">
            <el-button @click="outExport">导出</el-button> <!-- 确保调用 outExport -->
        </div>
        <!-- 表格展示 -->
        <el-table :data="outstockdata" stripe style="margin-top: 10px;" @selection-change="outSelectChange">
            <!-- 固定列和数据展示列 -->
            <el-table-column fixed type="selection"></el-table-column>
            <el-table-column fixed type="index" label="序号" width="80"></el-table-column>
            <el-table-column fixed label="出库单号" width="200px">
                <template #default="scope">
                    <span>{{ scope.row.out_code }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed prop="out_type" label="出库类型"></el-table-column>
            <el-table-column fixed prop="out_status" label="状态"></el-table-column>
            <el-table-column fixed prop="out_date" label="出库日期" width="180px"></el-table-column>
            <el-table-column prop="wh_name" label="仓库名称" width="150px"></el-table-column>
            <el-table-column prop="out_order" label="关联单号" width="200px"></el-table-column>
            <el-table-column label="出库货品" width="300px">
                <template #default="scope">
                    <el-tooltip
                        effect="dark"
                        :content="scope.row.proc_list_full"
                        placement="top"
                        :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                    >
                        <span>{{ scope.row.proc_list }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="out_user" label="经办人"></el-table-column>
            <el-table-column prop="out_num" label="出库数量"></el-table-column>
            <el-table-column prop="out_total" label="出库金额" width="120px"></el-table-column>
            <el-table-column prop="create_name" label="制单人"></el-table-column>
            <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
            <el-table-column prop="approver_name" label="审核人"></el-table-column>
            <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
        </el-table>
        <!-- 出库记录合计行 -->
        <div class="summary-row">
              <span>合计</span>
              <div>
                  <span class="summary-item">总出库数量: <b style="color: #e6a23c;">{{ outstockSummary.totalNum }}</b></span>
                  <span class="summary-item">总出库金额: <b style="color: #e6a23c;">{{ outstockSummary.totalAmount }}</b></span>
              </div>
          </div>
      </div>
      <div v-if="activeTab === '入库记录'" class="tab-content">
          <!--仅保留导出按钮和表格展示-->
          <div style="text-align: left; margin-bottom: 10px;">
              <el-button @click="inExport">导出</el-button> <!-- 确保调用 inExport -->
          </div>
          <!--表格展示部分保留只读展示-->
          <el-table :data="instockdata" stripe style="margin-top: 10px;" @selection-change="inSelectChange">
            <!--固定列和数据展示列保留-->
            <el-table-column fixed type="selection"></el-table-column>
            <el-table-column fixed type="index" label="序号" width="100"></el-table-column>
            <el-table-column fixed label="入库单号" width="200px">
                <template #default="scope">
                    <span>{{ scope.row.in_code }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed prop="in_type" label="入库类型"></el-table-column>
            <el-table-column fixed prop="in_status" label="状态"></el-table-column>
            <el-table-column fixed prop="in_date" label="入库日期" width="200px"></el-table-column>
            <el-table-column prop="wh_name" label="仓库名称" width="200px"></el-table-column>
            <el-table-column prop="in_order" label="关联单号" width="200px"></el-table-column>
            <el-table-column label="入库货品" width="300px">
                <template #default="scope">
                    <el-tooltip
                        effect="dark"
                        :content="scope.row.proc_list_full"
                        placement="top"
                        :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                    >
                        <span>{{ scope.row.proc_list }}</span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="in_user" label="经办人"></el-table-column>
            <el-table-column prop="in_num" label="入库数量"></el-table-column>
            <el-table-column prop="in_total" label="入库金额" width="120px"></el-table-column>
            <el-table-column prop="create_name" label="制单人"></el-table-column>
            <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
            <el-table-column prop="approver_name" label="审核人"></el-table-column>
            <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
        </el-table>
        <!-- 入库记录合计行 -->
        <div class="summary-row">
              <span>合计</span>
              <div>
                  <span class="summary-item">总入库数量: <b style="color: #e6a23c;">{{ instockSummary.totalNum }}</b></span>
                  <span class="summary-item">总入库金额: <b style="color: #e6a23c;">{{ instockSummary.totalAmount }}</b></span>
              </div>
          </div>
      </div>
    </div>
    <!-- 底部操作栏 -->
    <div class="action-bar">
      <el-button @click="Close">关闭</el-button>
    </div>
  </div>
</template>
<script>
import { useRouter, useRoute } from 'vue-router'
import {ref,reactive,onMounted, computed} from 'vue'; // 引入 computed
import http from '../auth/index';
import { ElMessage,ElMessageBox  } from 'element-plus'; //提示信息
import { Document } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx';
export default {
  setup(){
    const router = useRouter();
    const route = useRoute(); // 获取路由实例
    const id = ref(route.query ? route.query.id || null : null);
    // 选项卡数据
    const tabs = ['其他信息', '调拨明细', '出库记录', '入库记录'];
    const activeTab = ref('调拨明细');
    // 过滤条件
    const filter = reactive({
      operationType: '',
      operator: '',
      operationTime: ''
    });
    // 操作记录数据
    const filelist = ref([])//附件存储数组
    // 行点击事件
    function handleRowClick(row) {
      if (!row.file_name) {
        ElMessage.error('文件URL不存在，请重新上传');
        return;
      }
      const ext = row.title.split('.').pop().toLowerCase();
      switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
        case 'bmp':
        case 'pdf':
        case 'doc':
        case 'docx':
        case 'xls':
        case 'xlsx':
        case 'ppt':
        case 'txt':
        case 'pptx':
          window.open(row.file_name, '_blank');
          break;
        default:
          const link = document.createElement('a');
          link.href = row.file_name;
          link.download = row.title;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
      }
    }
    // 获取附件数据的方法
    function GetPublicFile() {
      const code = route.query ? route.query.code || null : null
      http.get("/PublicFile/GetPublicFileBy", {
        params: {
          type: "调拨",
          code: code,
        }
      }).then(res => {
        // 根据映射类调整数据结构
        console.log("附件:", res.data); // 调试用
        filelist.value = res.data;
      }).catch(err => {
        console.log(err)
        ElMessage.error('附件加载失败')
      })
    }
    const pageSize = ref(10);
    const totalItems = ref(100);
    const supplierForm = reactive({
        al_id:null,
        al_code:"",
        al_type:"",
        al_date:"",
        out_wh_id:null,
        out_wh_name:"",
        in_wh_id:null,
        in_wh_name:"",
        al_user:"",
        al_categories:null, // 调拨种类
        al_num:null,        // 调拨数量
        al_total:"",        // 调拨总金额
        al_outstockOK_num:null,
        al_outstockNO_num:null,
        al_instockOK_num:null,
        al_instockNO_num:null,
        instock_status:null,
        outstock_status:null,
        al_status:null,
        create_name:"",
        create_time:"",
        update_name:"",
        update_time:"",
        approver_name:"",
        approver_time:"",
        is_delete:null,
        remark:"",
        al_status_label:""
    });
    function GetId() {
      http.get("/Allot_h/GetId", {
          params: {
              id: id.value
          }
      }).then(res => {
          const apiData = res.data;
          console.log("ID调拨:", apiData); // 调试用
          Object.assign(supplierForm, processAllotData(apiData));
      }).catch(err => {
          console.log("ID调拨:",err);
          ElMessage.error('数据加载失败');
      });
    }
    //单据状态对应方法 单据状态存储字段:status.value
    // 封装数据处理逻辑
    function processAllotData(apiData) {
      const statusItem = status.value.find(item => item.dict_value == apiData.al_status);
      const statusLabel = statusItem ? statusItem.dict_label : "未知状态";
      return {
        al_id:apiData.al_id,
        al_code:apiData.al_code,
        al_type:apiData.al_type,
        al_date:formatDateTime(apiData.al_date),
        out_wh_id:apiData.out_wh_id,
        out_wh_name:apiData.out_wh_name,
        in_wh_id:apiData.in_wh_id,
        in_wh_name:apiData.in_wh_name,
        al_user:apiData.al_user,
        al_categories:apiData.al_categories, // 调拨种类
        al_num:apiData.al_num,               // 调拨数量
        al_total:parseFloat(apiData.al_total).toFixed(2), // 调拨总金额 (格式化)
        al_outstockOK_num:apiData.al_outstockOK_num,
        al_outstockNO_num:apiData.al_outstockNO_num,
        al_instockOK_num:apiData.al_instockOK_num,
        al_instockNO_num:apiData.al_instockNO_num,
        instock_status:apiData.instock_status,
        outstock_status:apiData.outstock_status,
        al_status:apiData.al_status,
        create_name:apiData.create_name,
        create_time:formatDateTime(apiData.create_time),
        update_name:apiData.update_name,
        update_time:formatDateTime(apiData.update_time),
        approver_name:apiData.approver_name,
        approver_time:formatDateTime(apiData.approver_time),
        is_delete:apiData.is_delete,
        remark:apiData.remark,
        al_status_label: statusLabel  // 添加状态标签
      };
    }
    // 删除调拨方法
    function deleteAllot() {
      ElMessageBox.confirm('确定要删除该调拨吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(async () => {
          try {
          // 调用后端逻辑删除接口（PUT 方法）
          const res = await http.put('/Allot/GetDelete?id='+id.value);
          if (res.status === 200) {
              ElMessage.success('删除成功');
              router.push('supplier');
          }
          } catch (err) {
          ElMessage.error('删除失败');
          console.error(err);
          }
      }).catch(() => {
          ElMessage.success('删除已取消');
      });
    }
    //跳转到编辑页面
    function JumptoEdit() {
      router.push({ path: 'allotupdate', query: { id: id.value ,Detail:true} });
    }
    // 日期转换格式 - 增强版，支持多种日期格式输入
    function formatDateTime(dateInput) {
      // 如果输入为空，返回空字符串
      if (!dateInput) return '';
      let date;
      // 如果输入是字符串，尝试解析
      if (typeof dateInput === 'string') {
        // 尝试解析ISO格式字符串 (如 "2023-08-15T12:34:56.789Z")
        date = new Date(dateInput);
        // 如果解析失败，尝试其他格式（如时间戳字符串）
        if (isNaN(date.getTime())) {
          // 尝试解析时间戳（毫秒）
          const timestamp = parseInt(dateInput);
          if (!isNaN(timestamp)) {
            date = new Date(timestamp);
          }
        }
      }
      // 如果输入是数字（时间戳）
      else if (typeof dateInput === 'number') {
        date = new Date(dateInput);
      }
      // 如果已经是Date对象
      else if (dateInput instanceof Date) {
        date = dateInput;
      }
      // 如果仍然无法解析，返回原始值或空字符串
      if (!date || isNaN(date.getTime())) {
        console.warn('无法解析日期:', dateInput);
        return dateInput || '';
      }
      // 格式化日期时间
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    // 货品列表格式化函数
    function formatProductList(products) {
        if (!products) return "";
        const productArray = Array.isArray(products)
            ? products
            : products.split('、').filter(Boolean);
        if (productArray.length <= 3) {
            return productArray.join('、');
        } else {
            const firstThree = productArray.slice(0, 3).join('、');
            return `${firstThree}等${productArray.length}项....`;
        }
    }
    //查询所有单据状态
    const status=ref([]);
    function GetStatus(){
        return http.get("/DictData/GetAllDictDataBytype?typeid=6")
        .then(res=>{
            status.value=res.data;
        }).catch(err=>{
            console.log(err);
        })
    }
    //查询所有出库状态
    const outstockstatusdata=ref([]);
    function outstockstatus() {
        http.get("/Supplier/GetDictData", {
            params: {
                dict_id: 14
            }
        }).then(res => {
            console.log("出库:", res.data); // 调试用
            outstockstatusdata.value = res.data; // 将查询结果赋值给 Departmentdata
        }).catch(err => {
            console.log(err);
            ElMessage.error('数据加载失败');
        });
    }
    //查询所有入库状态
    const instockstatusdata=ref([]);
    function instockstatus() {
        http.get("/Supplier/GetDictData", {
            params: {
                dict_id: 15
            }
        }).then(res => {
            console.log("入库:", res.data); // 调试用
            instockstatusdata.value = res.data; // 将查询结果赋值给 Departmentdata
        }).catch(err => {
            console.log(err);
            ElMessage.error('数据加载失败');
        });
    }
    function getStatusLabel(value, dict) {
      const found = dict.find(item => item.dict_value == value);
      return found ? found.dict_label : "未知状态";
    }
    const purform=reactive({
        code:"",
        ordstatus:"",
        sup:"",
        date:[null,null]
    })
    //表格数据
    const purdata = ref([]);
    //当前页
    const currentPage = ref(1);
    //查询数据
    async function GetAD(){
      try {
        const res = await http.get(`/Allot_d/GetAllot_d?id=${id.value}`);
        if (res.data?.length) {
          console.log("从表:", res.data);
          // 1. 获取货品ID数组
          const productIds = res.data.map(item => item.proc_id);
          console.log("货品ID列表:", productIds);
          // 2. 安全获取货品详情
          const params = new URLSearchParams();
          productIds.forEach(id => params.append('proc_ids', id));
          const productsRes = await http.get("/Product/GetPIds", { params });
          console.log("货品详情响应:", productsRes.data);
          // 3. 构建货品详情的映射，以 proc_id 为键
          const productMap = {};
          productsRes.data.forEach(p => {
            productMap[p.proc_id] = p;
          });
          // 4. 获取调入仓库库存
          const inStockRes = await http.get("/Stock/GetStockwhid", {
            params: { wh_id: supplierForm.in_wh_id }
          });
          console.log("显示调入:", inStockRes.data);
          // 5. 获取调出仓库库存
          const outStockRes = await http.get("/Stock/GetStockwhid", {
            params: { wh_id: supplierForm.out_wh_id }
          });
          console.log("显示调出:", outStockRes.data);
          // 6. 构建库存映射：按 proc_id 累加实际库存量
          const inStockMap = {};
          if (inStockRes.data?.length) {
            inStockRes.data.forEach(stock => {
              if (stock.proc_id && stock.stk_hand_num) {
                inStockMap[stock.proc_id] = (inStockMap[stock.proc_id] || 0) + stock.stk_hand_num;
              }
            });
          }
          const outStockMap = {};
          if (outStockRes.data?.length) {
            outStockRes.data.forEach(stock => {
              if (stock.proc_id && stock.stk_hand_num) {
                outStockMap[stock.proc_id] = (outStockMap[stock.proc_id] || 0) + stock.stk_hand_num;
              }
            });
          }
          // 7. 合并数据并添加库存字段
          purdata.value = res.data.map(detail => {
            const product = productMap[detail.proc_id] || {};
            // 查找入库状态名称
            const instock = instockstatusdata.value.find(
                ins => ins.dict_value == detail.instock_status
            );
            // 查找出库状态名称
            const outstock = outstockstatusdata.value.find(
                out => out.dict_value == detail.outstock_status
            );
            return {
              ...detail,
              ...product,
              out_wh_stock:outstock?.dict_label,
              in_wh_stock:instock?.dict_label,
              out_wh_num: outStockMap[detail.proc_id] || 0,
              in_wh_num: inStockMap[detail.proc_id] || 0
            };
          });
        }
        console.log("库存调拨明细:", purdata.value);
      } catch (error) {
        console.error("获取已添加货品失败:", error);
        ElMessage.error("获取已添加货品失败");
      }
    }
    //#region 查看详情信息
    function ShowInfo(row){
      router.push({
        name:"purchaseinfo",
        params:{
          purid:row.pur_id,
          purcode:row.pur_code
        }
      })
    }
    //导出：开始
    const selectdata = ref([]);

    // 处理表格选择变化 (调拨明细)
    function SelectChange(selectedRows) {
      selectdata.value = selectedRows;
    }

    // --- 修改后的导出方法 ---

    // 导出调拨明细 (用户选择的数据)
    function exportData() {
      if (selectdata.value.length === 0) {
        ElMessage.warning('请选择要导出的调拨明细数据');
        return;
      }

      // 映射选中的数据到 Excel 列
      const excelData = selectdata.value.map((row) => ({
        '序号': row.ald_id,
        '货品名称': row.proc_name,
        '货品编号': row.proc_code,
        '规格型号': row.proc_model,
        '单位': row.proc_primary_unit,
        '货品类型': row.type_name,
        '调出仓当前库存': row.out_wh_num,
        '调入仓当前库存': row.in_wh_num,
        '调拨数量': row.ald_num,
        '调拨单价': row.ald_price,
        '调拨金额': row.ald_total,
        '出库状态': `${row.out_wh_stock}(${row.ald_outstockOK_num}/${row.out_wh_num})`, // 根据模板拼接
        '入库状态': `${row.in_wh_stock}(${row.ald_instockOK_num}/${row.out_wh_num})`,   // 根据模板拼接
        '备注': row.remark
      }));

      // 创建工作簿和工作表
      const ws = XLSX.utils.json_to_sheet(excelData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "调拨明细");

      // 导出文件
      const filename = `调拨明细_${supplierForm.al_code || '未知单号'}_${new Date().toISOString().slice(0, 10)}.xlsx`;
      XLSX.writeFile(wb, filename);
    }
    //导出：结束
    //#region 入库记录
      // 数据格式化工具函数保留
      function formatGoodsList(goods) {
          if (!goods) return "";
          const goodsArray = Array.isArray(goods) ? goods : goods.split('、').filter(Boolean);
          if (goodsArray.length <= 3) {
              return goodsArray.join('、');
          } else {
              const firstThree = goodsArray.slice(0, 3).join('、');
              return `${firstThree}等${goodsArray.length}项....`;
          }
      }
      // 表格数据相关
      const instockdata = ref([]);
      const incurrentPage = ref(1);
      const inselectdata = ref([]);
      // 初始化数据加载（无条件加载全部数据）
      function InLoadData() {
        const code = route.query ? route.query.code || null : null;
        http.get("/Instock_h/GetAllInstock_hByCode", {
            params: {
                in_order: code
            }
        }).then(res => {
            // 添加空数组防护
            const listData = res.data?.list || [];
            const Data = listData.map(item => ({
                ...item,
                in_date: formatDateTime(new Date(item.in_date)),
                create_time: formatDateTime(new Date(item.create_time)),
                approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                in_total: item.in_total ? parseFloat(item.in_total).toFixed(2) : "0.00", // 格式化金额
                proc_list_full: item.proc_list,
                proc_list: formatGoodsList(item.proc_list)
            }));
            instockdata.value = Data;
        }).catch(error => {
            console.error("加载入库记录失败:", error);
            ElMessage.error("加载入库记录失败");
            instockdata.value = [];
        });
      }
      // 分页处理
      function inhandlePageChange(page) {
          incurrentPage.value = page;
          InLoadData();
      }
      // 多选数据收集
      function inSelectChange(val) {
          inselectdata.value = val;
      }
      // 导出功能
      function inExport() {
          if (inselectdata.value.length == 0) {
              ElMessage({ message: '请选择要导出的数据.', type: 'warning' });
              return;
          }
          const wb = XLSX.utils.book_new();
          const excelData = inselectdata.value.map((row) => ({
              "入库单号": row.in_code,
              "入库类型": row.in_type,
              "状态": row.in_status,
              "入库日期": row.in_date,
              "仓库名称": row.wh_name,
              "关联单号": row.in_order,
              "入库货品": row.proc_list,
              "经办人": row.in_user,
              "入库数量": row.in_num,
              "入库金额": row.in_total,
              "制单人": row.create_name,
              "制单时间": row.create_time,
              "审核人": row.approver_name,
              "审核时间": row.approver_time
          }));
          const ws = XLSX.utils.json_to_sheet(excelData);
          XLSX.utils.book_append_sheet(wb, ws, "入库单");
          XLSX.writeFile(wb, `入库单${new Date().toLocaleDateString()}.xlsx`);
      }
    //#endregion
    //#region 出库记录
      function formatGoodsList(goods) {
          if (!goods) return "";
          const goodsArray = Array.isArray(goods) ? goods : goods.split('、').filter(Boolean);
          if (goodsArray.length <= 3) {
              return goodsArray.join('、');
          } else {
              const firstThree = goodsArray.slice(0, 3).join('、');
              return `${firstThree}等${goodsArray.length}项....`;
          }
      }
      // 表格数据相关
      const outstockdata = ref([]);
      const outcurrentPage = ref(1);
      const outselectdata = ref([]);
      // 初始化数据加载
      function OutLoadData() {
        const code = route.query ? route.query.code || null : null;
        http.get("/Outstock_h/GetAllOutstock_hByCode", {
            params: {
                code: code
            }
        }).then(res => {
            // 添加空数组防护
            const listData = res.data?.list || [];
            const Data = listData.map(item => ({
                ...item,
                out_date: formatDateTime(new Date(item.out_date)),
                create_time: formatDateTime(new Date(item.create_time)),
                approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                out_total: item.out_total ? parseFloat(item.out_total).toFixed(2) : "0.00", // 格式化金额
                proc_list_full: item.proc_list,
                proc_list: formatGoodsList(item.proc_list)
            }));
            outstockdata.value = Data;
        }).catch(error => {
            console.error("加载出库记录失败:", error);
            ElMessage.error("加载出库记录失败");
            outstockdata.value = [];
        });
      }
      // 分页处理
      function outhandlePageChange(page) {
          outcurrentPage.value = page;
          OutLoadData();
      }
      // 多选数据收集
      function outSelectChange(val) {
          outselectdata.value = val;
      }
      // 导出功能
      function outExport() {
          if (outselectdata.value.length == 0) {
              ElMessage({ message: '请选择要导出的数据.', type: 'warning' });
              return;
          }
          const wb = XLSX.utils.book_new();
          const excelData = outselectdata.value.map((row) => ({
              "出库单号": row.out_code,
              "出库类型": row.out_type,
              "状态": row.out_status,
              "出库日期": row.out_date,
              "仓库名称": row.wh_name,
              "关联单号": row.out_order,
              "出库货品": row.proc_list,
              "经办人": row.out_user,
              "出库数量": row.out_num,
              "出库金额": row.out_total,
              "制单人": row.create_name,
              "制单时间": row.create_time,
              "审核人": row.approver_name,
              "审核时间": row.approver_time
          }));
          const ws = XLSX.utils.json_to_sheet(excelData);
          XLSX.utils.book_append_sheet(wb, ws, "出库单");
          XLSX.writeFile(wb, `出库单${new Date().toLocaleDateString()}.xlsx`);
      }
    //#endregion

    // === 新增的计算属性用于合计 ===
    // 调拨明细合计 (直接使用主表数据)
    const allotSummary = computed(() => {
      return {
        categories: supplierForm.al_categories || 0,
        totalNum: supplierForm.al_num || 0,
        totalAmount: supplierForm.al_total || '0.00'
      };
    });

    // 入库记录合计
    const instockSummary = computed(() => {
      if (!instockdata.value || instockdata.value.length === 0) {
          return {
              totalNum: 0,
              totalAmount: '0.00'
          };
      }
      const totalNum = instockdata.value.reduce((sum, item) => sum + (parseFloat(item.in_num) || 0), 0);
      const totalAmount = instockdata.value.reduce((sum, item) => sum + (parseFloat(item.in_total) || 0), 0);
      return {
          totalNum: totalNum,
          totalAmount: totalAmount.toFixed(2)
      };
    });

    // 出库记录合计
    const outstockSummary = computed(() => {
      if (!outstockdata.value || outstockdata.value.length === 0) {
          return {
              totalNum: 0,
              totalAmount: '0.00'
          };
      }
      const totalNum = outstockdata.value.reduce((sum, item) => sum + (parseFloat(item.out_num) || 0), 0);
      const totalAmount = outstockdata.value.reduce((sum, item) => sum + (parseFloat(item.out_total) || 0), 0);
      return {
          totalNum: totalNum,
          totalAmount: totalAmount.toFixed(2)
      };
    });
    // === 新增的计算属性结束 ===

    //挂载
    onMounted(async() => {
      InLoadData()
      OutLoadData()
      GetPublicFile()
      GetStatus()
      GetId()
      outstockstatus()
      instockstatus()
      await GetAD()
    });
    //关闭
    function Close(){
      router.back();
    }
    return{
      //#region 出库记录
      outstockdata,
      outhandlePageChange,
      outSelectChange,
      outExport,
      outstockSummary, // 暴露出库合计
      //#endregion
      //#region 入库记录
      incurrentPage,
      instockdata,
      inhandlePageChange,
      inselectdata,
      inSelectChange,
      inExport,
      instockSummary, // 暴露入库合计
      //#endregion
      selectdata,
      SelectChange,
      Close,
      ShowInfo,
      exportData,
      status,
      purform,
      purdata,
      handleRowClick,
      tabs,
      activeTab,
      filter,
      currentPage,
      pageSize,
      totalItems,
      supplierForm,
      GetId,
      deleteAllot,
      JumptoEdit,
      filelist,
      allotSummary // 暴露调拨明细合计
    }
  }
}
</script>
<style scoped>
/* 底部操作栏自适应 */
.action-bar {
  position: fixed;
  bottom: 0;
  right: 0.5%; /* 与表单右侧对齐 */
  left: 210px; /* 与菜单栏宽度一致 */
  background: white;
  border-top: 1px solid #e6e6e6;
  padding: 15px;
  text-align: right;
}
.supplier-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  width: 70%;
}
/* 通用样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}
.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 5px 0 15px;
}
/* 基础资料容器 */
.basic-info-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}
.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #1a1a1a;
}
.section-actions {
  display: flex;
  gap: 10px;
}
/* 灵活的基础资料网格布局 */
.basic-info-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 固定3列 */
  gap: 24px;
}
@media (max-width: 1200px) {
  .basic-info-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
@media (max-width: 768px) {
  .basic-info-grid {
    grid-template-columns: 1fr;
  }
}
.info-item {
  display: flex;
  min-height: 36px;
}
.info-label {
  width: 100px;
  color: #1a1a1a;
  font-size: 14px;
  display: flex;
  align-items: center;
}
.info-value {
  flex: 1;
  font-size: 14px;
  color: #a0a0a0;
  font-weight: 500;
  display: flex;
  align-items: center;
  padding-left: 10px;
}
/* 跨行显示的元素 */
.full-row {
  grid-column: 1 / -1;
  display: flex;
}
.full-row .info-label {
  width: 100px;
}
.full-row .info-value {
  flex: 1;
}
/* 其他信息容器 */
.other-info-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}
.section-tabs {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  width: 100%;
}
.tab-item {
  padding: 8px 20px;
  cursor: pointer;
  font-size: 14px;
  position: relative;
  color: #606266;
}
.tab-item.active {
  color: #45b984;
  font-weight: 500;
}
.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #45b984;
}
/* 灵活的基础资料网格布局 */
.Additional-Information {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 固定3列 */
  gap: 24px;
}
@media (max-width: 1200px) {
  .Additional-Information {
    grid-template-columns: repeat(2, 1fr);
  }
}
@media (max-width: 768px) {
  .Additional-Information {
    grid-template-columns: 1fr;
  }
}
/* 操作记录部分 */
.filter-section {
  margin-bottom: 20px;
}
.filter-row {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  align-items: center;
  flex-wrap: wrap;
}
.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}
.filter-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}
/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  margin-top: 20px;
}
.total-items {
  color: #606266;
  font-size: 14px;
}
.page-size-select {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
  gap: 8px;
}

/* === 新增的合计行样式 === */
.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  font-size: 14px;
  background-color: #f5f7fa; /* 可选：添加背景色以区分 */
  border-top: 1px solid #ebeef5; /* 可选：添加顶部边框 */
  margin-top: 10px; /* 与表格间距 */
}
.summary-row > span {
  font-weight: bold;
}
.summary-item {
  margin-left: 25px;
  color: #606266;
}
.summary-item > b {
  font-weight: bold;
}
/* === 新增的合计行样式结束 === */
</style>